package com.link.server.ws.handle.impl;

import com.link.common.core.LinkResponse;
import com.link.common.packet.RequestOperate;
import com.link.common.packet.ResponseOperate;
import com.link.common.packet.resp.SimplePacketResp;
import com.link.common.util.BinaryUtils;
import com.link.database.service.DBAccountService;
import com.link.database.service.DBCharacterService;
import com.link.server.ws.handle.HandleComponent;
import com.link.server.ws.handle.Handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;
@HandleComponent(RequestOperate.CHANNEL_LOGIN)
public class ChannelLoginHandle implements Handler {
    @Value("${link.login-server}")
    private String loginServer;

    private RestTemplate  restTemplate=new RestTemplate();

    @Resource
    private DBCharacterService characterService;
    @Resource
    private DBAccountService accountService;
    @Override
    public   void invoke(RequestOperate operate, ByteBuf packet, ChannelHandlerContext ctx) throws  Exception{
        var regionId= packet.readShort();
        var token= BinaryUtils.readString(packet);
        var result= restTemplate.getForObject(loginServer+"/token/valid?token="+token, LinkResponse.class);
        if(result.isSuccess()){
            int accountId= (int) result.data();

            var account = accountService.selectById( accountId);

            ctx.channel().attr(Handler.ACCOUNT_KEY).set(account);

            ctx.channel().attr(Handler.TOKEN_KEY).set(token);
             this.send(ctx, SimplePacketResp.response(ctx,ResponseOperate.CHANNEL_LOGIN, (short) 200));





        }else{
            this.send(ctx, SimplePacketResp.response(ctx,ResponseOperate.CHANNEL_LOGIN, (short) 400));
        }
    }
}
